/*
* @file Loudspeaker.cpp
* @brief This file contains the implementation of the Loudspeaker class
* @author feiniao
* @version 1.0
* @date 2025-5-11
* @note This code is designed to work with ESP32-S3 and uses the ESP-IDF 5.2.3 framework.
*/


#include "Loudspeaker.h"


/*
* @brief Constructor for the Loudspeaker class
*        Initializes the I2S driver with the specified configuration
* @param bck_io_num GPIO number for the BCK pin
* @param ws_io_num GPIO number for the WS pin
* @param data_in_num GPIO number for the DATA pin
* @param data_out_num GPIO number for the DATA pin
* @param sample_rate Sample rate for I2S communication
* @param i2s_port I2S port number
* @param i2s_mode I2S mode (master/slave)
*/
Loudspeaker::Loudspeaker() : loudspeaker(BCLK_PIN, LRC_PIN, -1, DIN_PIN, SAMPLE_RATE, loudspeaker_I2S_Port, (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), I2S_BITS_PER_SAMPLE_16BIT)
{
    ESP_LOGI(TAG, "Loudspeaker initialized");
}


/*
* @brief Destructor for the Loudspeaker class
*/
Loudspeaker::~Loudspeaker()
{
    ESP_LOGI(TAG, "Loudspeaker destroyed");
}


/*
* @brief Play audio data using the I2S interface
* @param buffer Pointer to the audio data buffer
* @param bytes_to_write Number of bytes to write to the I2S interface
* @note This function writes the audio data to the I2S interface for playback.
*       It uses the BSP_I2S interface to send audio samples to the I2S driver.
*       The function returns ESP_OK on success or an error code on failure.
*/
esp_err_t Loudspeaker::play(const void* buffer, size_t bytes_to_write)
{
    esp_err_t ret = loudspeaker.write(buffer, bytes_to_write);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "播放失败: %s", esp_err_to_name(ret));
    }
    ESP_LOGI(TAG, "播放中...");
    return ret;
}
